<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElIcon, ElCard, ElButton, ElForm, ElFormItem, ElInput, ElSkeleton, ElEmpty } from 'element-plus';
import { Loading, Refresh, CircleCloseFilled } from '@element-plus/icons-vue';
import creditService from '@/services/creditService';
import { userManager } from '@/utils/user';
import { methods } from '@/utils/methods';

const currentPoem = ref(null);
const userAnswers = reactive({ answers: [] });
const isSubmitting = ref(false);
const poetryFormRef = ref(null);

const isLoading = ref(true);
const loadError = ref(null);

const fetchNewPoem = async () => {
  isLoading.value = true;
  loadError.value = null;
  currentPoem.value = null;

  try {
    // 【核心修正】调用了正确的函数名 getPoetryQuestion
    const response = await creditService.getPoetryQuestion();
    if (response.code === 1000 && response.data) {
      currentPoem.value = response.data;
      userAnswers.answers = currentPoem.value.lines.map(line =>
          line.type === 'input' ? '' : null
      );
      if (poetryFormRef.value) {
        poetryFormRef.value.resetFields();
      }
    } else {
      loadError.value = response.msg || '获取题目失败，请检查网络或联系管理员。';
    }
  } catch (error) {
    console.error('获取新题目失败:', error);
    loadError.value = '网络请求失败，请稍后刷新重试。';
  } finally {
    isLoading.value = false;
  }
};

const submitAnswers = async () => {
  if (!poetryFormRef.value) return;

  isSubmitting.value = true;
  try {
    await poetryFormRef.value.validate();

    const submittedAnswers = userAnswers.answers.filter(answer => answer !== null);
    const responseData = await creditService.submitPoetryChallenge(currentPoem.value.id, submittedAnswers);

    if (responseData.code === 1000) {
      ElMessage.success({message: responseData.msg || '回答正确！', center: true});
      creditService.addNewCredit(1, null, methods.ANCIENT_POETRY_MEMORIZATION, userManager.getUserId(), (res) => {
        if (res.code === 1000) {
          ElMessage.success({message: res.msg || '恭喜您，全部正确，已获得1学分！', center: true});
        }
      });
      setTimeout(fetchNewPoem, 1500);
    } else {
      ElMessage.error({message: responseData.msg || '抱歉，答案有误，请重新尝试！', center: true});
    }
  } catch (error) {
    console.log('表单验证失败或请求错误:', error);
  } finally {
    isSubmitting.value = false;
  }
};

onMounted(fetchNewPoem);
</script>

<template>
  <div class="page-background">
    <div class="poetry-container">
      <el-card shadow="never" class="poetry-card">
        <template #header>
          <div class="card-header">
            <span>古诗词背诵挑战</span>
            <el-button
                type="primary"
                plain
                round
                @click="fetchNewPoem"
                :disabled="isSubmitting || isLoading"
                :icon="Refresh"
            >
              换一首
            </el-button>
          </div>
        </template>

        <div v-if="isLoading" class="status-placeholder">
          <el-skeleton :rows="5" animated/>
        </div>
        <div v-else-if="loadError" class="status-placeholder">
          <el-empty :description="loadError">
            <el-button type="primary" round @click="fetchNewPoem">重试</el-button>
          </el-empty>
        </div>
        <div v-else-if="currentPoem" class="poem-content">
          <h3 class="poem-title">{{ currentPoem.title }}</h3>
          <p class="author-dynasty">{{ currentPoem.author }} · {{ currentPoem.dynasty }}</p>

          <el-form :model="userAnswers" ref="poetryFormRef" class="poem-form">
            <div v-for="(line, index) in currentPoem.lines" :key="index" class="poem-line">
              <span v-if="line.type === 'text'" class="poem-text">{{ line.content }}</span>
              <el-form-item
                  v-else-if="line.type === 'input'"
                  class="poem-input-item"
                  :prop="'answers.' + index"
                  :rules="[{ required: true, message: '此句不能为空', trigger: 'blur' }]"
              >
                <el-input
                    v-model="userAnswers.answers[index]"
                    :placeholder="line.placeholder"
                    class="poem-input"
                    :disabled="isSubmitting"
                />
              </el-form-item>
            </div>

            <el-button
                type="primary"
                class="submit-button"
                @click="submitAnswers"
                :loading="isSubmitting"
                size="large"
                round
            >
              提交答案
            </el-button>
          </el-form>
        </div>
      </el-card>
    </div>
  </div>
</template>

<style scoped>
/* 建议在全局CSS中引入字体，以避免网络问题 */
/* @import url('https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@400;500;700&display=swap'); */

.page-background {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(180deg, #f8f9fb 0%, #f4f6f9 100%);
  padding: 24px;
  font-family: 'Noto Serif SC', 'Source Han Serif SC', 'Songti SC', serif;
}

.poetry-container {
  width: 100%;
  max-width: 720px;
}

.poetry-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -2px rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 1.2rem;
  font-weight: 500;
  color: #202124;
}

.poem-content {
  padding: 24px 32px;
  text-align: center;
}

.poem-title {
  font-size: 2rem;
  font-weight: 700;
  color: #2c3e50;
  margin-bottom: 8px;
}

.author-dynasty {
  font-size: 1rem;
  color: #5f6368;
  margin-bottom: 48px;
}

.poem-form {
  margin: 0 auto;
}

.poem-line {
  margin-bottom: 32px;
  font-size: 1.5rem;
  line-height: 1.8;
  color: #34495e;
  display: flex;
  justify-content: center;
  align-items: center;
}

.poem-input-item {
  width: 100%;
  max-width: 450px;
  margin: 0 auto;
}

.poem-input :deep(.el-input__wrapper) {
  background-color: transparent;
  box-shadow: none;
  border-radius: 0;
  padding: 0;
  border-bottom: 1.5px solid #dcdfe6;
  transition: border-color 0.2s;
}

.poem-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: none !important;
  border-bottom-color: var(--el-color-primary);
}

.poem-input :deep(.el-input__inner) {
  text-align: center;
  font-family: 'Noto Serif SC', 'Source Han Serif SC', 'Songti SC', serif;
  font-size: 1.2rem;
  color: #34495e;
  height: 40px;
  line-height: 40px;
}

.submit-button {
  margin-top: 24px;
  width: 220px;
  height: 44px;
  font-size: 1.1rem;
  font-weight: 500;
}

.status-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}
</style>